package com.mq.rabbitmq.srcdemo;
import java.io.IOException;
import java.util.concurrent.TimeoutException;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.ConsumerCancelledException;
import com.rabbitmq.client.QueueingConsumer;
import com.rabbitmq.client.QueueingConsumer.Delivery;
import com.rabbitmq.client.ShutdownSignalException;

/**
 * 接收消息
 * @author zhoufeng
 *
 */
public class Receive {

    /**
     * 这种机制自动确认报异常之后，还是会消费；
     * @param args
     * @throws IOException
     * @throws ShutdownSignalException
     * @throws ConsumerCancelledException
     * @throws InterruptedException
     */
    public static void main(String[] args) throws IOException, ShutdownSignalException, ConsumerCancelledException, InterruptedException {
        ConnectionFactory connFac = new ConnectionFactory() ;
        connFac.setHost("127.0.0.1");
        Connection conn = null;
        try {
            conn = connFac.newConnection();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }
        Channel channel = conn.createChannel() ;
        String channelName = "channel01";
        channel.queueDeclare(channelName, true, false, false, null) ;
        //配置好获取消息的方式
        QueueingConsumer consumer = new QueueingConsumer(channel) ;
        //取消 autoAck
        boolean autoAck = false ;
        channel.basicConsume(channelName, true, consumer) ;

        //循环获取消息
        while(true){
            //获取消息，如果没有消息，这一步将会一直阻塞
            System.out.println("start cost");
            Delivery delivery = consumer.nextDelivery() ;
            String s = null;
            s.toString();
//            String msg = new String(delivery.getBody()) ;
//            //确认消息，已经收到
//            String s = null;
//             s.toString();
           // channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
            //System.out.println("received message[" + msg + "] from " + channelName);
        }
    }
}